import React, { Component } from 'react';
import { DatePicker, Form, Input, message, Select, Upload, Icon, Button } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import {
  createCase,
  getAreaList,
  getAttachmentList,
  getTypeList,
  updateCase,
  uploadAttachment,
} from '@/pages/routes/table/service';
import { EnumObject } from '@/pages/routes/table/QueryForm';
import TextArea from 'antd/es/input/TextArea';
import { GetFieldDecoratorOptions, ValidateFieldsOptions } from 'antd/es/form/Form';
import EquTable from './equ-table';
import { Moment } from 'moment';
import { ValueObject } from '@/pages/routes/table/interface';
import OrgTable from '@/pages/routes/table/equ-table/OrgTable';
import { UploadFile } from 'antd/es/upload/interface';

export interface ViewProps extends FormComponentProps {
  initialValue?: ValueObject;
  isEdit?: boolean;
}

export const defaultValue: ValueObject = {
  name: '',
  type: -1,
  area: -1,
  startDate: undefined,
  endDate: undefined,
  ds: [],
  ts: [],
  hf: [],
  scdd: '',
  gwyx: '',
  scyx: '',
  bmzz: [],
  mark: '',
};

interface FormInfoState {
  areaList: EnumObject[];
  typeList: EnumObject[];
  fileList: UploadFile[];
}

class FormInfo extends Component<ViewProps, FormInfoState> {
  public state: FormInfoState = {
    areaList: [],
    typeList: [],
    fileList: [],
  };

  //表单提交的逻辑，创建数据和修改数据
  public handleSubmit = (e: any) => {
    const { isEdit } = this.props;
    const { fileList } = this.state;
    if (fileList.length) {
      uploadAttachment({
        attachment: fileList[0].originFileObj as File,
        objectId: String(5),
        f: 'json',
        remark: '',
        dbtype: 2,
        dir: '',
        type: 'mspt',
        filename: 'whx',
      }).then(res => {
        console.log(res);
      });

      getAttachmentList({ objectId: 5 }).then(res => {
        console.log(res);
      });
    }
    this.props.form.validateFields(async (err: any, value: ValueObject) => {
      if (err) return;
      console.log(fileList);
      if (isEdit) {
        console.log('edit', value);
        const { code, msg, data } = await updateCase(value);
        if (code === -1) {
          message.error('方案创建失败');
          return;
        }
        message.success('创建成功！');
        //
      } else {
        console.log('create', value);
        const { code, msg, data } = await createCase(value);
        if (code === -1) {
          message.error('方案创建失败');
          return;
        }
        message.success('创建成功！');
        //
      }
    });
    e.preventDefault();
    console.log(e);
  };

  componentDidMount() {
    this.loadAreaList();
    this.loadTypeList();
  }

  render() {
    const initialValue = this.props.initialValue || defaultValue;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { areaList, typeList } = this.state;

    const startDateOptions: GetFieldDecoratorOptions = {
      rules: [{ required: true, message: '请输入开始时间' }],
    };
    if (initialValue.startDate) {
      startDateOptions.initialValue = initialValue.startDate;
    }

    const endDateOptions: GetFieldDecoratorOptions = {
      rules: [{ required: true, message: '请输入结束时间' }],
    };
    if (initialValue.startDate) {
      endDateOptions.initialValue = initialValue.startDate;
    }

    return (
      <div>
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} onSubmit={this.handleSubmit}>
          <Form.Item label="方案名称">
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入方案名称' }],
              initialValue: initialValue.name,
            })(<Input placeholder={'请输入'} />)}
          </Form.Item>
          <Form.Item label="方案类型">
            {getFieldDecorator('type', {
              initialValue: initialValue.type,
              rules: [{ required: true, message: '请输入方案类型' }],
            })(
              <Select>
                {typeList.map((v) => (
                  <Select.Option value={v.value} key={v.value}>
                    {v.title}
                  </Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="所属区域">
            {getFieldDecorator('area', {
              initialValue: initialValue.area,
              rules: [{ required: true, message: '请输入所属区域' }],
            })(
              <Select>
                {areaList.map((v) => (
                  <Select.Option value={v.value} key={v.value}>
                    {v.title}
                  </Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="开始时间">
            {getFieldDecorator('startDate', startDateOptions)(<DatePicker onChange={this.onChange} />)}
          </Form.Item>
          <Form.Item label="结束时间">
            {getFieldDecorator('endDate', endDateOptions)(<DatePicker onChange={this.onChange} />)}
          </Form.Item>
          <Form.Item label="调水">
            {getFieldDecorator('ds', {
              valuePropName: 'dataSource',
              trigger: 'onChange',
              initialValue: initialValue.ds,
            })(<EquTable />)}
          </Form.Item>
          <Form.Item label="停水">
            {getFieldDecorator('ts', {
              valuePropName: 'dataSource',
              trigger: 'onChange',
              initialValue: initialValue.ts,
            })(<EquTable />)}
          </Form.Item>
          <Form.Item label="恢复">
            {getFieldDecorator('hf', {
              valuePropName: 'dataSource',
              trigger: 'onChange',
              initialValue: initialValue.hf,
            })(<EquTable />)}
          </Form.Item>
          <Form.Item label="水厂、加压站调度">
            {getFieldDecorator('scdd', {
              rules: [{ required: false, message: '请输入开始时间' }],
              initialValue: initialValue.scdd,
            })(<TextArea placeholder={'请输入'} />)}
          </Form.Item>
          <Form.Item label="管网影响">
            {getFieldDecorator('gwyx', {
              rules: [{ required: false, message: '请输入开始时间' }],
              initialValue: initialValue.gwyx,
            })(<TextArea placeholder={'请输入'} />)}
          </Form.Item>
          <Form.Item label="水厂、加压站影响">
            {getFieldDecorator('scyx', {
              rules: [{ required: false, message: '请输入开始时间' }],
            })(<TextArea placeholder={'请输入'} />)}
          </Form.Item>
          <Form.Item label="部门职责">
            {getFieldDecorator('bmzz', {
              valuePropName: 'dataSource',
              trigger: 'onChange',
              initialValue: initialValue.bmzz,
            })(<OrgTable />)}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('mark', {
              initialValue: initialValue.mark,
            })(<Input placeholder={'请输入'} />)}
          </Form.Item>
          <Form.Item label="附件">
            <Upload
              beforeUpload={() => false}
              onChange={({ fileList }) => {
                this.setState({ fileList });
              }}
            >
              <Button>
                <Icon type="to-top" style={{ marginRight: 5 }} />
                请上传文件
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }

  private onChange = () => {
    console.log('我是选择器');
  };

  private async loadAreaList() {
    try {
      const { code, data } = await getAreaList();
      if (code === 0) {
        this.setState({ areaList: [{ title: '全部', value: -1 }].concat(data) });
        return;
      }
      message.error('获取区域列表失败了');
    } catch (e) {
      console.error(e);
      message.error('获取区域列表失败了');
    }
  }

  public async loadTypeList() {
    try {
      const { code, data } = await getTypeList();
      if (code === 0) {
        this.setState({ typeList: [{ title: '全部', value: -1 }].concat(data) });
        return;
      }
      message.error('获取方案类型列表失败了');
    } catch (e) {
      console.error(e);
      message.error('获取方案类型列表失败了');
    }
  }
}

// const DForm = Form.create()(FormInfo) as any as FormInfo;
export default Form.create<ViewProps>()(FormInfo);
